package com.cckat.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * Date:2022/10/4
 * Author:ybc
 * Description:
 */
@Configuration //将当前类标识为配置类
@EnableWebSecurity //开启注解配置Spring security
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启注解控制权限
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //密码加密程序，用于验证用户输入的密码是否正确
    @Bean //将当前方法的返回值配置为一个bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /*@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication() //使用内存中设置的用户名和密码
                .withUser("admin") //用户名
                //.password("{noop}123456") //密码，{noop}表示使用明文的密码
                .password(new BCryptPasswordEncoder().encode("123456"))
                .authorities("role.edit"); //授权

    }*/

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //调用父类的configure()，即使用SpringSecurity中默认的功能
        //super.configure(http);
        http.authorizeRequests()
                .antMatchers("/static/**", "/login").permitAll() //匿名访问的资源，即不登录就可以访问的资源
                .anyRequest().authenticated(); //其他所有的请求都必须认证才能访问，即登录之后才能访问
        //设置自定义的登录页面
        http.formLogin()
                .loginPage("/login") //设置登录页面的请求路径
                .loginProcessingUrl("/login_process") //设置验证登录功能的请求路径
                .defaultSuccessUrl("/") //设置登录成功默认跳转到的页面
                .failureUrl("/login"); //设置登录失败跳转到的页面
        //设置注销功能
        http.logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login");
        //将csrf功能禁用
        http.csrf().disable();
        //允许iframe嵌套
        http.headers().frameOptions().disable();
        //设置访问被拒绝时的处理程序
        http.exceptionHandling().accessDeniedHandler(new CckatAccessDeniedHandler());
    }
}
